<?php

namespace App\Http\Controllers\Home;

use App\Http\Controllers\Controller;
use App\Http\Controllers\PaymentController;
use App\Http\Controllers\PlaceController;
use App\Http\Controllers\SmsController;
use App\Http\Controllers\UploadController;
use App\Models\BrowseJob;
use App\Models\CollArea;
use App\Models\CollPosition;
use App\Models\CompanyBasic;
use App\Models\CompanyJob;
use App\Models\CompanyUser;
use App\Models\Interview;
use App\Models\PersonalLoginRecord;
use App\Models\PersonalUser;
use Tymon\JWTAuth\Facades\JWTAuth;
use App\Models\User;
use App\Models\UserRanks;
use App\Models\UserSuggests;
use App\Models\WebConfig;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Validator, DB, Redis;

class UserController extends CommonController
{
    /**
     * 个人详情
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(Request $request)
    {
        $uid = $request->uid;
        $info = User::select('uid', 'name', 'nickname', 'mobile', 'avatar', 'status', 'created_at', 'updated_at')->where('uid', $uid)
            ->first();

        $urankInfo = DB::table('user_ranks')->where('uid', $uid)->where('status', 1)->orderBy('id', 'desc')->first();
        $vipName = '';
        $isVip = 0;
        $deadTime = 0;
        if ($urankInfo) {
            $isVip = 1;
            $vipInfo = DB::table('vip_info')->where('id', $urankInfo->rank)->first();

            $vipName = $vipInfo->name;
            $deadTime = date('Y-m-d', strtotime($urankInfo->created_at) + $vipInfo->days * 86400);
        }
        $info->vip_name = $vipName;
        $info->is_vip = $isVip;
        $info->deadTime = $deadTime;
        return response()->json(['status' => 1, 'data' => $info]);
    }

    /**
     * 重置密码
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function resetPwd(Request $request)
    {
        $input = $request->only(['mobile', 'code', 'password']);
        if (!$input['mobile'] || !$input['code'] || !$input['password']) {
            return response()->json(['status' => 0, 'msg' => '参数缺失']);
        }

        $uinfo = User::where('mobile', $input['mobile'])->select('uid', 'password')->first();
        if (!$uinfo) {
            return response()->json(['status' => 0, 'msg' => '该账户不存在！']);
        }

        $sms = new SmsController();
        $res = $sms->checkCode($input['mobile'], $input['code']);
        if ($res['status'] == 0) {
            return response()->json(['status' => 0, 'msg' => $res['msg']]);
        }

        if (Hash::check($input['password'], $uinfo->password)) {
            return response()->json(['status' => 0, 'msg' => '新密码与原密码一致！']);
        }

        $npwd = Hash::make($input['password']);

        $result = User::where('uid', $uinfo->uid)->update(['password' => $npwd]);
        if ($result) {
            return response()->json(['status' => 1, 'msg' => '重置成功！']);
        } else {
            return response()->json(['status' => 0, 'msg' => '重置失败！']);
        }
    }

    /**
     * 用户注册
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function register(Request $request)
    {
        $input = $request->only(['mobile', 'code', 'password']);

        $rules = [
            'mobile' => 'required|size:11',
            'code' => 'required',
            'password' => 'required|min:6',
//            'repassword' => 'required|min:6',
        ];
        $messages = [
            'mobile.required' => '手机号码必填',
            'mobile.size' => '手机号码为11位',
            'code.required' => '短信验证码必填',
            'password.required' => '登录密码必填',
            'password.min' => '登录密码不能少于6位数',
//            'repassword.required' => '确认密码必填',
//            'repassword.min' => '确认密码不能少于6位数'
        ];

        $validate = Validator::make($input, $rules, $messages);
        if ($error = $validate->errors()->first()) {
            return response()->json(['status' => 0, 'msg' => $error]);
        }

//        if ($input['password'] != $input['repassword']) {
//            return response()->json(['status' => 0, 'msg' => '登录密码和确认密码不一致！']);
//        }

        $user = User::where('mobile', $input['mobile'])->first();
        if ($user) {
            return response()->json(['status' => 0, 'msg' => '该手机号码已注册']);
        }

        $sms = new SmsController();
        $res = $sms->checkCode($input['mobile'], $input['code']);
        if ($res['status'] == 0) {
            return response()->json(['status' => 0, 'msg' => $res['msg']]);
        }

        DB::beginTransaction();
        try {
            //注册并登录
            $nickname = '用户' . time();
            $pdata = User::create([
                'name' => $input['mobile'],
                'nickname' => $nickname,
                'mobile' => $input['mobile'],
                'password' => Hash::make($input['password']),
                'wechatid' => 0,
                'last_login_time' => date('Y-m-d H:i:s', time()),
                'regip' => $request->ip(),
                'last_login_ip' => $request->ip()
            ]);

            DB::commit();
        } catch (\Exception $e) {
            //接收异常处理并回滚
            DB::rollBack();
            return response()->json(['status' => 0, 'msg' => '注册失败']);
        }

        $token = JWTAuth::fromUser($pdata);
        if (!$token) {
            return response()->json(['status' => 0, 'msg' => '注册成功！请登录！']);
        }

        return response()->json(['status' => 1, 'msg' => '注册成功！登录成功！', 'token' => $token]);
    }

    /**
     * 更新头像
     * @return array
     */
    public function changeHeadimg(Request $request)
    {
        $headimg = $request->headimg;
        if (!$headimg) {
            return response()->json(['status' => 0, 'msg' => '参数缺失']);
        }
        User::where('uid', $request->uid)->update(['avatar' => $headimg]);
        return response()->json(['status' => 1, 'msg' => '更新成功']);
    }

    /**
     * 更新昵称和姓名
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function updateMemberMsg(Request $request)
    {
        $nickname = trim($request->nickname);
        $name = trim($request->name);
        if (!$nickname || !$name) {
            return response()->json(['status' => 0, 'msg' => '参数缺失']);
        }

        $uid = $request->uid;
        $res = User::where('uid', $uid)->update(['nickname' => $nickname, 'name' => $name]);
        if ($res) {
            return response()->json(['status' => 1, 'msg' => '更新成功']);
        } else {
            return response()->json(['status' => 0, 'msg' => '更新失败']);
        }
    }

    /**
     * 更新性别
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function changeSex(Request $request)
    {
        $sex = trim($request->sex);
        if (!$sex) {
            return response()->json(['status' => 0, 'msg' => '参数缺失']);
        }

        $uid = $request->uid;
        $uinfo = Resume::where('uid', $uid)->select('realname')->first();

        if ($uinfo->sex == $sex) {
            return response()->json(['status' => 0, 'msg' => '性别未改变！']);
        }

        $res = Resume::where('uid', $request->uid)->update(['sex' => $sex]);
        if ($res) {
            self::toStatus($request->uid);
            return response()->json(['status' => 1, 'msg' => '更新成功']);
        } else {
            return response()->json(['status' => 0, 'msg' => '更新失败']);
        }
    }

    /**
     * 更新工作年限
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function changeWork(Request $request)
    {
        $experience = trim($request->experience);
        if (!$experience) {
            return response()->json(['status' => 0, 'msg' => '参数缺失']);
        }

        $uid = $request->uid;
        $uinfo = Resume::where('uid', $uid)->select('work_year')->first();

        if ($uinfo->work_year == $experience) {
            return response()->json(['status' => 0, 'msg' => '工作年限未改变！']);
        }

        $res = Resume::where('uid', $request->uid)->update(['work_year' => $experience]);
        if ($res) {
            self::toStatus($request->uid);
            return response()->json(['status' => 1, 'msg' => '更新成功']);
        } else {
            return response()->json(['status' => 0, 'msg' => '更新失败']);
        }
    }

    /**
     * 更新联系方式
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function changeMobile(Request $request)
    {
        $mobile = trim($request->mobile);
        if (!$mobile) {
            return response()->json(['status' => 0, 'msg' => '参数缺失']);
        }

        $uid = $request->uid;
        $umobile = PersonalUser::where('uid', $uid)->value('mobile');

        if ($umobile == $mobile) {
            return response()->json(['status' => 0, 'msg' => '联系方式未改变！']);
        }

        $person = PersonalUser::where('mobile', $mobile)->where('uid', '!=', $mobile)->select('uid')->get();
        if (count($person) > 0) {
            return response()->json(['status' => 0, 'msg' => '该联系方式已存在！']);
        }

        $res = PersonalUser::where('uid', $uid)->update(['mobile' => $mobile]);
        if ($res) {
            Resume::where('uid', $uid)->update(['mobile' => $mobile]);
            self::toStatus($request->uid);
            return response()->json(['status' => 1, 'msg' => '更新成功']);
        } else {
            return response()->json(['status' => 0, 'msg' => '更新失败']);
        }
    }

    /**
     * 更新简介
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function changeIntroduce(Request $request)
    {
        $introduce = trim($request->introduce);
        if (!$introduce) {
            return response()->json(['status' => 0, 'msg' => '参数缺失']);
        }

        $uid = $request->uid;

        $res = Resume::where('uid', $uid)->update(['introduction' => $introduce]);
        if ($res) {
            self::toStatus($request->uid);
            return response()->json(['status' => 1, 'msg' => '更新成功']);
        } else {
            return response()->json(['status' => 0, 'msg' => '更新失败']);
        }
    }

    /**
     * 更新出生日期
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function changeBorth(Request $request)
    {
        $borth = trim($request->borth);
        if (!$borth) {
            return response()->json(['status' => 0, 'msg' => '参数缺失']);
        }

        $borth = date('Y-m-d', strtotime($borth));

        $uid = $request->uid;
        $res = Resume::where('uid', $uid)->update(['birthday' => $borth]);
        if ($res) {
            self::toStatus($request->uid);
            return response()->json(['status' => 1, 'msg' => '更新成功']);
        } else {
            return response()->json(['status' => 0, 'msg' => '更新失败']);
        }
    }

    /**
     * 更新工作地点
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function changeJobarea(Request $request)
    {
        $area = $request->area;
        if (!$area) {
            return response()->json(['status' => 0, 'msg' => '参数缺失']);
        }

        $data['jobarea1'] = $area;
        $uid = $request->uid;

        $address = CollArea::getAreaAddress($area);
        $place = new PlaceController();
        $id = $place->getLocation($address);

        if (!$id) {
            return response()->json(['status' => 0, 'msg' => '地址解析错误！']);
        }

        $data['ip_id'] = $id;

        $res = Resume::where('uid', $uid)->update($data);
        if ($res) {
            self::toStatus($request->uid);
            return response()->json(['status' => 1, 'msg' => '更新成功']);
        } else {
            return response()->json(['status' => 0, 'msg' => '更新失败']);
        }
    }

    /**
     * 更新工种
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function changeJobsort(Request $request)
    {
        $position = trim($request->position);
        if (!$position) {
            return response()->json(['status' => 0, 'msg' => '参数缺失']);
        }

        $uid = $request->uid;
        $res = Resume::where('uid', $uid)->update(['jobsort1' => $position]);
        if ($res) {
            self::toStatus($request->uid);
            return response()->json(['status' => 1, 'msg' => '更新成功']);
        } else {
            return response()->json(['status' => 0, 'msg' => '更新失败']);
        }
    }

    /**
     * 更新期望薪资
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function changeExpectsalary(Request $request)
    {
        $salary = trim($request->salary);
        if (!$salary) {
            return response()->json(['status' => 0, 'msg' => '参数缺失']);
        }

        $uid = $request->uid;
        $res = Resume::where('uid', $uid)->update(['expectedsalary' => $salary]);
        if ($res) {
            self::toStatus($request->uid);
            return response()->json(['status' => 1, 'msg' => '更新成功']);
        } else {
            return response()->json(['status' => 0, 'msg' => '更新失败']);
        }
    }

    public function changeid1(Request $request)
    {
        $id1 = trim($request->path);
        if (!$id1) {
            return response()->json(['status' => 0, 'msg' => '参数缺失']);
        }

        $uid = $request->uid;
        $res = Resume::where('uid', $uid)->update(['id1' => $id1]);
        if ($res) {
            return response()->json(['status' => 1, 'msg' => '更新成功']);
        } else {
            return response()->json(['status' => 0, 'msg' => '更新失败']);
        }
    }

    public function changeID2(Request $request)
    {
        $id1 = trim($request->path);
        if (!$id1) {
            return response()->json(['status' => 0, 'msg' => '参数缺失']);
        }

        $uid = $request->uid;
        $res = Resume::where('uid', $uid)->update(['ID2' => $id1]);
        if ($res) {
            return response()->json(['status' => 1, 'msg' => '更新成功']);
        } else {
            return response()->json(['status' => 0, 'msg' => '更新失败']);
        }
    }

    public function toStatus($uid)
    {
        $info = DB::table('personal_users as p')
            ->join('resume as r', 'p.uid', '=', 'r.uid')
            ->select(
                'p.uid', 'p.mobile',
                'r.realname', 'r.sex', 'r.avatar', 'r.resume_status', 'r.birthday', 'r.work_year', 'r.introduction', 'r.jobarea1', 'r.jobsort1', 'r.expectedsalary'
            )->where('p.uid', $uid)
            ->first();

        if ($info->avatar && $info->realname && $info->sex && $info->birthday && $info->work_year && $info->mobile) {
            if (in_array($info->resume_status, [0, 2])) {
                Resume::where('uid', $uid)->update(['resume_status' => 1]);
            }

            if ($info->jobarea1 && $info->jobsort1) {
                $resumeStatus = DB::table('personal_users as p')
                    ->join('resume as r', 'p.uid', '=', 'r.uid')
                    ->where('p.uid', $uid)
                    ->value('resume_status');

                if (in_array($resumeStatus, [0, 1])) {
                    Resume::where('uid', $uid)->update(['resume_status' => 2]);
                }
            }
        }
    }

    /**
     * 认证申请
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function authReply(Request $request)
    {
        $uid = $request->uid;
        $info = DB::table('personal_users as p')
            ->join('resume as r', 'p.uid', '=', 'r.uid')
            ->select(
                'p.uid', 'p.mobile',
                'r.realname', 'r.sex', 'r.avatar', 'r.resume_status', 'r.birthday', 'r.work_year', 'r.introduction', 'r.jobarea1', 'r.jobsort1', 'r.expectedsalary', 'r.id1', 'r.ID2'
            )->where('p.uid', $uid)
            ->first();

        if (!in_array($info->resume_status, [2])) {
            return response()->json(['status' => 0, 'msg' => '暂时不可申请！']);
        }

        if (!($info->id1 && $info->ID2)) {
            return response()->json(['status' => 0, 'msg' => '请先上传身份证！']);
        }

        Resume::where('uid', $uid)->update(['resume_status' => 3]);
        return response()->json(['status' => 1, 'msg' => '申请成功']);
    }

    /**
     * 我的预约
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function appointJobs(Request $request)
    {
        $page = $request->page;
        $start = ($page - 1) * self::$totalList;

        $uid = $request->uid;
        $jobsr = DB::table('resume_send as t1')
            ->join('company_job as t2', 't1.job_id', '=', 't2.id')
            ->join('company_basic as t3', 't2.com_id', '=', 't3.id')
            ->join('company_users as t4', 't2.uid', '=', 't4.uid')
            //获取字段
            ->select(
                't2.id', 't2.job_title', 't2.job_category1', 't2.location1', 't2.address', 't2.salary', 't2.description', 't2.welfare', 't2.updatetime', 't2.job_status', 't2.begin_date', 't2.ip_id',
                't3.company_name', 't3.logo',
                't4.mobile'
            )
            ->where('t2.job_status', 5)
            ->where('t1.personal_uid', $uid)
            ->orderBy('id', 'desc')
            ->skip($start)
            ->take(self::$totalList)
            ->get();

        if (count($jobsr) > 0) {
            foreach ($jobsr as $k => $v) {
                //地区
                $v->location = CollArea::getAreaName($v->location1);

                if (trim($v->location) == '') {
                    $v->location = "地区不限";
                }
                if ($v->address) {
                    $v->location = $v->location . ' ' . $v->address;
                }

                $v->job_category1 = CollPosition::getPosName($v->job_category1);

                $latlngInfo = DB::table('latlng_info')->where('id', $v->ip_id)->first();
                $maps = [];
                if ($latlngInfo) {
                    $maps[] = explode(',', $latlngInfo->auto_navi);
                    $maps[] = explode(',', $latlngInfo->tencent);
                    $maps[] = explode(',', $latlngInfo->baidu);
                }

                $v->ip_maps = $maps;
            }
        }

        $totalCount = DB::table('resume_send as t1')
            ->join('company_job as t2', 't1.job_id', '=', 't2.id')
            ->join('company_basic as t3', 't2.com_id', '=', 't3.id')
            //获取字段
            ->where('t2.job_status', 5)
            ->where('t1.personal_uid', $uid)
            ->count();

        return response()->json(['status' => 1, 'data' => ['list' => $jobsr, 'totalCount' => $totalCount]]);
    }

    /**
     * 我的所有工作订单
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function jobs(Request $request)
    {

        $page = $request->page;
        $start = ($page - 1) * self::$totalList;

        $uid = $request->uid;
        $status = $request->status;
        $jobsr = DB::table('resume_send as t1')
            ->join('company_job as t2', 't1.job_id', '=', 't2.id')
            ->join('company_basic as t3', 't2.com_id', '=', 't3.id')
            //获取字段
            ->select(
                't2.id', 't2.job_title', 't2.job_category1', 't2.location1', 't2.address', 't2.salary', 't2.description', 't2.welfare', 't2.updatetime', 't2.job_status',
                't3.company_name', 't3.logo'
            )
            ->where(function ($query) use ($status) {
                if ($status >= 10) {
                    $query->where('t2.job_status', $status);
                } else {
                    $query->where('t2.job_status', '>=', 10);
                }
            })
            ->where('t1.personal_uid', $uid)
            ->orderBy('id', 'desc')
            ->get()->toArray();

        array_walk($jobsr, function (&$valuer, $key) {
            $valuer->type = 1;
        });

        $jobsi = DB::table('interview as t1')
            ->join('company_job as t2', 't1.job_id', '=', 't2.id')
            ->join('company_basic as t3', 't2.com_id', '=', 't3.id')
            //获取字段
            ->select(
                't2.id', 't2.job_title', 't2.job_category1', 't2.location1', 't2.address', 't2.salary', 't2.description', 't2.welfare', 't2.updatetime', 't2.job_status',
                't3.company_name', 't3.logo'
            )
            ->where('personal_uid', $uid)
            ->where(function ($query) use ($status) {
                if ($status >= 10) {
                    $query->where('t2.job_status', $status);
                } else {
                    $query->where('t2.job_status', '>=', 10);
                }
            })
            ->orderBy('id', 'desc')
            ->get()->toArray();

        array_walk($jobsi, function (&$valuei, $key) {
            $valuei->type = 2;
        });

        $company_jobs = array_merge($jobsr, $jobsi);
        if ($company_jobs) {
            $id = 0;
            foreach ($company_jobs as $k => $v) {
                if ($v->id == $id) {
                    unset($company_jobs[$k]);
                } else {
                    $id = $v->id;
                }
            }
        }

        $sort = array_column($company_jobs, 'id');
        array_multisort($sort, SORT_DESC, $company_jobs);

        $company_job = count($company_jobs) > 0 ? array_slice($company_jobs, $start, self::$totalList) : [];
        if (count($company_job) > 0) {
            foreach ($company_job as $k => $v) {
                //地区
                $v->location = CollArea::getAreaName($v->location1);

                if (trim($v->location) == '') {
                    $v->location = "地区不限";
                }
                if ($v->address) {
                    $v->location = $v->location . ' ' . $v->address;
                }

                $v->job_category1 = CollPosition::getPosName($v->job_category1);
            }
        }

        return response()->json(['status' => 1, 'data' => $company_job]);
    }

    /**
     * 邀请列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function interviews(Request $request)
    {

        $page = $request->page;
        $start = ($page - 1) * self::$totalList;

        $uid = $request->uid;
        $interview = DB::table('interview as t1')
            ->join('company_basic as t2', 't1.com_id', '=', 't2.id')
            ->join('company_job as t3', 't1.job_id', '=', 't3.id')
            ->select(
                't1.status',
                't3.id', 't3.job_title', 't3.job_category1', 't3.location1', 't3.address', 't3.salary', 't3.description', 't3.welfare', 't3.updatetime',
                't2.company_name', 't2.logo'
            )
            ->where('t1.personal_uid', $uid)
            ->where('t1.status', '!=', 4)
            ->orderBy('updated_at', 'desc')
            ->skip($start)->take(self::$totalList)
            ->get();

        if ($interview) {
            foreach ($interview as $k => $v) {
                //地区
                $v->location = CollArea::getAreaName($v->location1);

                if (trim($v->location) == '') {
                    $v->location = "地区不限";
                }
                if ($v->address) {
                    $v->location = $v->location . ' ' . $v->address;
                }

                if ($v->logo) {
                    $v->logo = 'https://ldlw.hnliandesy.com/upload/companylogo/' . $v->logo;
                } else {
                    $v->logo = '';
                }

                $v->job_category1 = CollPosition::getPosName($v->job_category1);

                $v->interview_status = $v->status;
            }
        }

        return response()->json(['status' => 1, 'data' => $interview]);
    }

    /**
     * 是否查看过某工作
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function isChecked(Request $request)
    {
        $uid = $request->uid;
        $jodId = $request->job_id;
        $Interview = Interview::where('personal_uid', $uid)->select('id')->where('job_id', $jodId)->where('status', 0)->first();
        if ($Interview->id) {
            Interview::where('id', $Interview->id)->update(['status' => 1]);
            return response()->json(['status' => 1, 'msg' => '状态更新成功']);
        } else {
            return response()->json(['status' => 0, 'msg' => '更新失败']);
        }
    }

    /**
     * 处理邀请
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function interviewHandle(Request $request)
    {
        $uid = $request->uid;
        $input = $request->only('job_id', 'status');

        $interviewInfo = Interview::where('personal_uid', $uid)->where('job_id', $input['job_id'])->first();

        if (!$interviewInfo) {
            return response()->json(['status' => 0, 'msg' => "该邀请不存在！"]);
        }
        if (in_array($interviewInfo->status, [2, 3]) && in_array($input['status'], [0, 1, 2, 3])) {
            return response()->json(['status' => 0, 'msg' => "该操作非法！"]);
        }

        $jobInfo = CompanyJob::select('id', 'job_status', 'job_title')
            ->where('id', $interviewInfo->job_id)
            ->first();

        if (!$jobInfo) {
            return response()->json(['status' => 0, 'msg' => "该项目不存在！"]);
        }

        if ($jobInfo->job_status != 1) {
            return response()->json(['status' => 0, 'msg' => "该项目暂不可参与！"]);
        }

        if ($input['status'] == 2) {
            $reInfo = ResumeSend::select('status')
//                ->where('com_id', $interviewInfo->com_id)
                ->where('personal_uid', $interviewInfo->personal_uid)
                ->where('job_id', $interviewInfo->job_id)
                ->whereIn('status', [2, 10])
                ->count();
            if ($reInfo > 0) {
                return response()->json(['status' => 0, 'msg' => "您的简历投递已被聘用，不可同意邀请！"]);
            }
        }

        $result = Interview::where('id', $interviewInfo->id)->update(['status' => $input['status']]);
        if ($result) {
            if ($input['status'] == 2) {
                CompanyJob::where('id', $interviewInfo->job_id)->update(['job_status' => 10]);

                $time = date('Y-m-d H:i:s');
                $comInfo = CompanyBasic::where('id', $interviewInfo->com_id)->first(['mobile', 'company_name']);

                //公司
                if ($comInfo->mobile) {
                    $content = "尊敬的{$comInfo->company_name}：您好！您的项目{$jobInfo->job_title}邀请的工人已于{$time}同意您的邀请，请及时登录网站查看信息！";
                    $sms = new SmsController();
                    $sms->sendMsg($comInfo->mobile, urlencode($content));
                }
            }

            return response()->json(['status' => 1, 'msg' => "操作成功"]);
        } else {
            return response()->json(['status' => 0, 'msg' => "操作失败"]);
        }
    }

    /**
     * 提现申请
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function withdraw(Request $request)
    {
        $uid = $request->uid;
        $money = $request->money;
        $bankId = $request->bank_id;
        if (!$money || !$bankId) {
            return response()->json(['status' => 0, 'msg' => '参数缺失！']);
        }
        if ($money <= 0) {
            return response()->json(['status' => 0, 'msg' => '提现金额输入错误！']);
        }

        $resumeStatus = Resume::where('uid', $uid)->value('resume_status');
        if ($resumeStatus == 0) {
            return response()->json(['status' => 10, 'msg' => '请先完成个人信息！']);
        } elseif ($resumeStatus == 1) {
            return response()->json(['status' => 11, 'msg' => '请先完成工作信息！']);
        } elseif ($resumeStatus == 2) {
            return response()->json(['status' => 12, 'msg' => '请先完成实名认证！']);
        } elseif ($resumeStatus == 3) {
            return response()->json(['status' => 13, 'msg' => '等待后台认证审核！']);
        }

        $wInfo = DB::table('withdraw')->where('uid', $uid)->where('status', 0)->first();
        if ($wInfo) {
            return response()->json(['status' => 0, 'msg' => '上次提现尚未审核！']);
        }

        $begin = date('Y-m-d', strtotime('today'));
        $wInfo = DB::table('withdraw')->where('uid', $uid)->whereDate('addtime', $begin)->first();

        if ($wInfo) {
            return response()->json(['status' => 0, 'msg' => '今日提现次数已用完！']);
        }

        $hasmoney = PersonalUser::where('uid', $uid)->value('hasmoney');

        if ($hasmoney < $money) {
            return response()->json(['status' => 0, 'msg' => '提现金额超出余额！']);
        }

        DB::beginTransaction();
        try {
            PersonalUser::where('uid', $uid)->decrement('hasmoney', $money);

            $wData = [
                'uid' => $uid,
                'bank_id' => $bankId,
                'money' => $money,
                'addtime' => date('Y-m-d H:i:s', time()),
                'updatetime' => date('Y-m-d H:i:s', time()),
                'status' => 1
            ];

            $id = DB::table('withdraw')->insertGetId($wData);
            DB::commit();

            $hasmoney = PersonalUser::where('uid', $uid)->value('hasmoney');
            $type = array('recordtype' => 0, 'changetype' => 50, 'moneytype' => 1);
            $moneyArr = array('money' => $money, 'hasmoney' => $hasmoney);
            $this->money_change($type, 0, $uid, $moneyArr, $id);
            unset($type, $moneyArr);

            $result = $this->approvedWd($id);
            if ($result) {
                return response()->json(['status' => 1, 'msg' => '提现成功！']);
            }

            $pdata = [
                'hasmoney' => $hasmoney + $money,
            ];

            $res = PersonalUser::where('uid', $uid)->update($pdata);
            if ($res) {
                DB::table('withdraw')->where('id', $id)->update(['status' => -1]);

                $hasmoney = PersonalUser::where('uid', $uid)->value('hasmoney');
                $type = array('recordtype' => 1, 'changetype' => 51, 'moneytype' => 1);
                $moneyArr = array('money' => $money, 'hasmoney' => $hasmoney);
                $this->money_change($type, 0, $uid, $moneyArr, $id);
                unset($type, $moneyArr);

                return response()->json(['status' => 0, 'msg' => '提现失败！']);
            } else {
                return response()->json(['status' => 0, 'msg' => '数据还原失败！']);
            }
        } catch (Exception $e) {
            DB::rollback();
            throw $e;
            return response()->json(['status' => 0, 'msg' => '提现申请失败！']);
        }
    }

    public function approvedWd($id)
    {
        $wdInfo = DB::table('withdraw')->where('id', $id)->first(['status', 'money', 'bank_id']);
        if ($wdInfo->status != 1) {
            return false;
        }

        $redisField = 'wd_' . $id;
        $isWd = Redis::exists($redisField);

        if ($isWd) {
            return false;
        }

        Redis::set($redisField, date('Y-m-d H:i:s', time()));

        $bankInfo = DB::table('banks')->select('bank_id', 'bank_holder', 'bank_number')->where('id', $wdInfo->bank_id)->first();
        $code = DB::table('bank_list')->where('id', $bankInfo->bank_id)->value('number');

        $data = [
            'bank_no' => $bankInfo->bank_number,
            'true_name' => $bankInfo->bank_holder,
            'bank_code' => $code,
            'money' => $wdInfo->money,
        ];

        $payMent = new PaymentController();
        $result = $payMent->payBank($data);

        if ($result['return_code'] == 'FAIL' && $result['result_code'] == 'FAIL') {
            return false;
        }

        DB::table('withdraw')->where('id', $id)->update(['partner_trade_no' => $result['partner_trade_no'], 'payment_no' => $result['payment_no']]);

        return true;
    }

    /**
     * 添加银行卡
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function addBank(Request $request)
    {
        $uid = $request->uid;
        $bankId = $request->bankid;
        $bankHolder = $request->bankholder;
        $bankNumber = $request->banknumber;
        if (!$bankId || !$bankHolder || !$bankNumber) {
            return response()->json(['status' => 0, 'msg' => '参数缺失！']);
        }

        $mobile = trim($request->mobile);
        $code = trim($request->code);
        if (!$mobile || !$code) {
            return response()->json(['status' => 0, 'msg' => '手机号码或者短信验证码缺失！']);
        }

        if (strlen($mobile) != 11) {
            return response()->json(['status' => 0, 'msg' => '手机号码必须是11位数！']);
        }
        preg_match("/1[3-9]{1}\d{9}/", $mobile, $result);
        if (!$result) {
            return response()->json(['status' => 0, 'msg' => '手机号码格式错误！']);
        }

        $sms = new SmsController();
        $res = $sms->checkCode($mobile, $code);
        if ($res['status'] == 0) {
            return response()->json(['status' => 0, 'msg' => $res['msg']]);
        }

        $bankInfo = DB::table('banks')->where('uid', $uid)->where('bank_number', $bankNumber)->first();
        if ($bankInfo) {
            return response()->json(['status' => 0, 'msg' => '该银行卡号已存在！']);
        }

        DB::beginTransaction();
        try {
            $bData = [
                'uid' => $uid,
                'bank_id' => $bankId,
                'bank_holder' => $bankHolder,
                'bank_number' => $bankNumber,
                'addtime' => date('Y-m-d H:i:s', time()),
                'updatetime' => date('Y-m-d H:i:s', time()),
            ];

            DB::table('banks')->insert($bData);
            DB::commit();
            return response()->json(['status' => 1, 'msg' => '添加成功！']);
        } catch (Exception $e) {
            DB::rollback();
            throw $e;
            return response()->json(['status' => 0, 'msg' => '添加失败！']);
        }
    }

    /**
     * 我的银行列表
     * @return \Illuminate\Http\JsonResponse
     */
    public function banks()
    {
        $lists = DB::table('banks')
            ->orderBy('id', 'desc')
            ->get();

        if (count($lists) > 0) {
            foreach ($lists as $v) {
                $v->bank_name = DB::table('bank_list')->where('id', $v->bank_id)->value('bank_name');
            }
        }

        return response()->json(['status' => 1, 'data' => $lists]);
    }

    /**
     * 提现记录
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function wdRecord(Request $request)
    {
        $totalList = 10;
        $page = $request->page;
        $start = ($page - 1) * $totalList;

        $uid = $request->uid;
        $status = $request->status;

        $records = DB::table('withdraw')
            //获取字段
            ->select('money', 'addtime', 'status')
            ->where('uid', $uid)
            ->where(function ($query) use ($status) {
                if (in_array($status, [-1, 0, 1])) {
                    $query->where('status', $status);
                }
            })
            ->orderBy('id', 'desc')
            ->skip($start)->take($totalList)->get();

        return response()->json(['status' => 1, 'data' => $records]);
    }

    /**
     * 用户反馈
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function suggesting(Request $request)
    {
        $uid = $request->uid;
        $content = $request->contents;

        if (!$content) {
            return response()->json(['status' => 0, 'data' => '请输入反馈内容！']);
        }

        $res = UserSuggests::create(['uid' => $uid, 'content' => $content]);
        if ($res) {
            return response()->json(['status' => 1, 'msg' => '反馈成功！']);
        } else {
            return response()->json(['status' => 0, 'msg' => '反馈失败！']);
        }
    }

    /**
     * 生成会员订单
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function createVip(Request $request)
    {
        $rank = $request->rank;
        if (!in_array($rank, [1, 2, 3])) {
            return response()->json(['status' => 0, 'msg' => '非法操作！']);
        }

        $uid = $request->uid;
        $tag = $this->create_order($uid);

        $data = [
            'order_number' => $tag,
            'uid' => $uid,
            'rank' => $rank,
            'status' => 0,
        ];

        $res = UserRanks::create($data);
        if ($res) {
            return response()->json(['status' => 1, 'msg' => '生成会员订单！', 'data' => $tag]);
        } else {
            return response()->json(['status' => 0, 'msg' => '操作失败！']);
        }
    }

    /**
     * 注销账号
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function deleteAccount(Request $request)
    {
        $uid = $request->uid;
        $res = User::where('uid', $uid)->update(['status' => -1]);
        if ($res) {
            return response()->json(['status' => 1, 'msg' => '注销成功']);
        } else {
            return response()->json(['status' => 0, 'msg' => '注销失败']);
        }
    }
}
